package com.suisung.shopsuite.trade.controller.front;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suisung.shopsuite.core.web.service.RedisService;
import com.suisung.shopsuite.trade.dao.LogisticsCallbackDao;
import com.suisung.shopsuite.trade.model.entity.LogisticsCallback;
import com.suisung.shopsuite.trade.service.OrderLogisticsService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 订单物流信息回调地址
 * </p>
 *
 * @author Why
 * @since 2018-07-04
 */

@Api(tags = "订单发货物流信息回调")
@RestController
@RequestMapping("/front/trade/logisticsCallBack")
public class CallbackController {

    @Resource
    private RedisService redisService;

    @Resource
    private LogisticsCallbackDao logisticsCallbackDao;

    @Resource
    private OrderLogisticsService orderLogisticsService;

    /*订单物流回调接口*/
    @RequestMapping("/getTrajectory")
    public HashMap<String, Object> getTrajectory(@RequestParam HashMap<String, Object> jsonparams) {

        System.out.println("--- 收到快递信息回调 ---");
        System.out.println(jsonparams.toString());
        System.out.println("--- 收到快递信息回调 ---");

        JSONObject jsonObject = JSONUtil.parseObj(jsonparams);

        /*返回数据集合*/
        HashMap<String, Object> resultMap = new HashMap<>();

        try {

            LogisticsCallback logisticsCallback = new LogisticsCallback();

            /*推送时间*/
            String PushTime = "";

            JSONObject RequestData = jsonObject.get("RequestData", JSONObject.class);

            if (null != RequestData) {

                PushTime = RequestData.get("PushTime", String.class);
                logisticsCallback.setPushTime(PushTime);

                /*当前推送信息内多有订单信息集合*/
                JSONArray datalist = RequestData.get("Data", JSONArray.class);

                datalist.forEach(bean -> {

                    JSONObject jsonBean = (JSONObject) bean;

                    /*成功与否 */
                    Boolean Success = jsonBean.get("Success", Boolean.class);

                    /*快递单号*/
                    String LogisticCode = jsonBean.get("LogisticCode", String.class);

                    /*快递公司编码*/
                    String ShipperCode = jsonBean.get("ShipperCode", String.class);

                    /*物流状态编码*/
                    String StateEx = jsonBean.get("StateEx") != null ? jsonBean.get("StateEx", String.class) : null;

                    /*物流状态
                      0-暂无轨迹信息
                      1-已揽收
                      2-在途中
                      3-签收
                      4-问题件
                      5-转寄
                      6-清关  */
                    String State = jsonBean.get("State", String.class);

                    /*用户ID*/
                    String EBusinessID = jsonBean.get("EBusinessID", String.class);

                    /*失败原因*/
                    String Reason = jsonBean.get("Reason") != null ? jsonBean.get("Reason", String.class) : null;

                    /*用户自定义回传字段*/
                    String Callback = jsonBean.get("Callback") != null ? jsonBean.get("Callback", String.class) : null;

                    /*Success 为 false*/
                    if (!Success) {

                        if (!"null".equalsIgnoreCase(State) && "0".equals(State)) {
                            /*若推送false，且State为0，属正常，等待下次推送即可。*/
                            System.out.println(LogisticCode + " ---> 等待下次推送 <---");

                        } else if (Reason.contains("三天无轨迹") || Reason.contains("七天内无轨迹变化")) {
                            /*若推送false，且Reason为“三天无轨迹”或“七天内无轨迹变化”，需重新发起订阅。*/

                            logisticsCallback.setLogisticCode(LogisticCode);
                            logisticsCallback.setReason(Reason);
                            logisticsCallback.setShipperCode(ShipperCode);

                            System.out.println("订单:" + LogisticCode + Reason + " ---> 需重新发起订阅 <---");
                            try {
                                if (!"null".equals(ShipperCode) && !"".equals(ShipperCode)){
                                    JSONObject take = orderLogisticsService.returnLogisticsByInter(ShipperCode, LogisticCode);

                                    if (!take.get("Success", Boolean.class)) {
                                        System.out.println(LogisticCode + "--- 订阅失败 ---");
                                    } else {
                                        System.out.println(LogisticCode + "--- 订阅成功 ---");
                                    }
                                }else {
                                    System.out.println(LogisticCode + "无订阅快递公司信息" + "--- 订阅失败 ---");
                                }

                            } catch (Exception e) {
                                System.out.println(LogisticCode + "--- 订阅失败 ---");
                                throw new RuntimeException(e);
                            }
                        }
                    } else {

                        /*当前订单轨迹集合*/
                        JSONArray Traces = jsonBean.get("Traces", JSONArray.class);

                        logisticsCallback.setLogisticCode(LogisticCode);
                        logisticsCallback.setShipperCode(ShipperCode);
                        logisticsCallback.setState(State);
                        logisticsCallback.setEbusinessId(EBusinessID);
                        logisticsCallback.setReason(Reason);
                        logisticsCallback.setCallback(Callback);
                        logisticsCallback.setTraces(JSONUtil.toJsonStr(Traces));
                        logisticsCallback.setStateEx(StateEx);

                        /*存放当前订单的所有物流轨迹信息*/
                        //ArrayList<String> callbacks = new ArrayList<>();

                        /*Traces.forEach(tracesBean -> {

                            JSONObject tracesbean = (JSONObject) tracesBean;

                            *//*轨迹描述*//*
                            String AcceptStation = String.valueOf(tracesbean.get("AcceptStation"));

                            *//*轨迹发生时间*//*
                            String AcceptTime = String.valueOf(tracesbean.get("AcceptTime"));

                            *//*备注*//*
                            String Remark = String.valueOf(tracesbean.get("Remark"));

                            *//*历史节点所在城市*//*
                            String Location = String.valueOf(tracesbean.get("Location"));

                            *//*历史节点物流状态编码*//*
                            String Action = String.valueOf(tracesbean.get("Action"));

                            logisticsCallback.setAcceptStation(AcceptStation);
                            logisticsCallback.setAcceptTime(AcceptTime);
                            logisticsCallback.setRemark(Remark);
                            logisticsCallback.setLocation(Location);
                            logisticsCallback.setAction(Action);

                            callbacks.add(JSONUtil.toJsonStr(logisticsCallback));

                        });*/

                        /*使用订单为key 将轨迹信息插入redis缓存*/
                        // redisService.set(LogisticCode, JSONUtil.toJsonStr(Traces));

                        /*将轨迹信息更新到数据库*/
                        QueryWrapper<LogisticsCallback> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("logistic_code", LogisticCode);

                        LogisticsCallback logcall = logisticsCallbackDao.selectOne(queryWrapper);

                        if (logcall != null) {
                            logcall.setTraces(JSONUtil.toJsonStr(Traces));
                            logisticsCallbackDao.updateById(logcall);

                        } else {
                            logisticsCallbackDao.insert(logisticsCallback);

                        }
                    }
                });

                resultMap.put("ShipperCode", "Yt0");
                resultMap.put("EBusinessID", "1857708");
                resultMap.put("Success", true);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String format = simpleDateFormat.format(new Date());
                resultMap.put("UpdateTime", format);

            } else {
                resultMap.put("data", "未获取到RequestData数据");
                resultMap.put("Success", true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("Success", false);
        }

        return resultMap;
    }
}
